package cn.sitcat.springbootshiro.configs;

import cn.sitcat.springbootshiro.model.User;
import cn.sitcat.springbootshiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author hiseico
 * @date 2019/4/13 18:07
 * @desc 自定义Realm
 */
public class UserRealm extends AuthorizingRealm {


    /**
     * 执行授权逻辑
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权：Authorization");

        //给资源进行授权
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        //添加资源的授权字符串
        //simpleAuthenticationInfo.addStringPermission("user:add");


        //从数据库查询当前登录的用户的授权字符串
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        User dbUser = userService.selectUserById(user.getId());

        simpleAuthenticationInfo.addStringPermission(dbUser.getPerms());

        return simpleAuthenticationInfo;
    }

    @Autowired
    private UserService userService;

    /**
     * 执行认证逻辑
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证：Authentiction");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userService.getUserByName(token.getUsername());
        if (user == null) {
            //用户不存在
            return null; // shiro底层会抛出UnknowAccountException
        }

        //判断密码
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
